package com.zboin.ucenter.config;

import com.zboin.ucenter.auth.SmsAuthenticationProvider;
import com.zboin.ucenter.auth.UsernamePasswordAuthenticationProvider;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.web.cors.CorsConfiguration;

import java.util.Arrays;

/**
 * @author zhboom
 * @date 2025/7/9 22:21
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private SmsAuthenticationProvider smsAuthenticationProvider;
    @Resource
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    @Bean
    public ProviderManager providerManager() {
        return new ProviderManager(Arrays.asList(smsAuthenticationProvider, usernamePasswordAuthenticationProvider));
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 禁用表单登录、退出、csrf、session管理等默认配置
        http
                .httpBasic(AbstractHttpConfigurer::disable)
                .formLogin(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .sessionManagement(AbstractHttpConfigurer::disable)
                .requestCache(cache -> cache.requestCache(new NullRequestCache()))
                .csrf(AbstractHttpConfigurer::disable)
                .anonymous(AbstractHttpConfigurer::disable);

        http
                .cors(cors -> cors.configurationSource(req -> {
                    CorsConfiguration conf = new CorsConfiguration();
                    conf.setAllowCredentials(true);
                    conf.addAllowedOrigin("*"); // 允许所有域名访问
                    conf.addAllowedHeader("*"); // 允许所有请求头
                    conf.addAllowedMethod("*"); // 允许所有请求方法
                    return conf;
                }))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/auth/**").permitAll()
                        .anyRequest().permitAll());
                // 在 UsernamePasswordAuthenticationFilter 之前添加 Filter
                // .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        // authenticationProvider
        http
                // 用于注册不同的认证方式
                .authenticationProvider(smsAuthenticationProvider)
                .authenticationProvider(usernamePasswordAuthenticationProvider);

        return http.build();
    }
}
